<?php

namespace backend\logic;

use think\Db;
use external\SFTools;

class UserAuthLogic {
    /**
     * 根据经销商编码和电话号码查询用户是否已经授权
     * @param   string $fccode 经销商编码
     * @param   string $phone  电话号码
     * @return  array          数组对象数据
     */
    public function getUserAuthFindBuyFccodeAndPhone($fccode, $phone) {
        $field = 'ua.*,u.login_account,u.nickname,u.accout_state';
        return Db::name('user_auth')->alias('ua')->field($field)->join('aip_user u', 'UA.user_uuid = u.user_uuid')->where('ua.fCCode', $fccode)->where('u.login_account', $phone)->find();
    }

    /**
     * 保存用户权限及保存用户资料
     * @param   string $fccode 经销商编码
     * @param   string $phone  电话号码
     * @return  array          数组对象数据
     */
    public function saveUserAuthFindBuyFccodeAndPhone($fccode, $phone) {
        Db::startTrans();
        $userLogic = new \backend\logic\UserLogic;
        $userFind = $userLogic->saveUserFind($phone);
        if (empty($userFind['user_uuid'])) {
            Db::rollback();
            return SFTools::err('3307');
        }
        else {
            $user_uuid = $userFind['user_uuid'];
            $userAuthFind = $this->saveUserAuthFind($fccode, $user_uuid);
            if (empty($userAuthFind)) {
                Db::rollback();
                return SFTools::err('3307');
            }
        }
        Db::commit();
        return $user_uuid;
    }

    /**
     * 根据经销商编码与用户唯一标识查询用户权限
     * @param   string $fccode    经销商编码
     * @param   string $user_uuid 用户唯一标识
     * @return  array             数组对象集合数据
     */
    public function getUserAuthListBuyFccodeAndUserUUID($fccode, $user_uuid) {
        $userAuth = new \backend\model\UserAuth;
        $field = 'user_auth_uuid,user_uuid,fCCode,is_private';
        return $userAuth::field($field)->where('user_uuid', $user_uuid)->where('fCCode', $fccode)->find();
    }

    /**
     * 保存用户权限
     * @param   string $fccode    经销商编码
     * @param   string $user_uuid 用户唯一标识
     * @return  array             数组对象数据
     */
    public function saveUserAuthFind($fccode, $user_uuid) {
        $userAuth = new \backend\model\UserAuth;
        $field = 'user_auth_uuid,user_uuid,fCCode,is_private';
        $userAuthFind = $userAuth::field($field)->where('user_uuid', $user_uuid)->where('fCCode', $fccode)->find();
        if (empty($userAuthFind)) {
            $userAuth->user_uuid = $user_uuid;
            $userAuth->fCCode = $fccode;
            $userAuth->save();
            $userAuthFind['user_auth_uuid'] = $userAuth->user_auth_uuid;
            $userAuthFind['user_uuid'] = $userAuth->user_uuid;
            $userAuthFind['fCCode'] = $userAuth->fCCode;
            $userAuthFind['is_private'] = 0;
        }
        return $userAuthFind;
    }

    /**
     * 获取用户授权列表
     * @param   array $userFind 用户对象
     * @return  array           数组集合对象数据
     */
    public function getUserAuthListBuyUserFind($userFind) {
        $user_uuid = $userFind['user_uuid'];
        $fccode = $userFind['fccode'];
        if (empty($user_uuid)) {
            return SFTools::err("3300");
        }
        if (empty($fccode)) {
            return SFTools::err("3300");
        }
        $field = 'ua.*,u.login_account,u.nickname,u.accout_state';
        $userAuthList = Db::name('user_auth')->alias('ua')->field($field)->join('aip_user u', 'UA.user_uuid = u.user_uuid')->where('u.user_uuid', $user_uuid)->order('create_time', 'ASC')->select();
        foreach ($userAuthList as $key => $value) {
            $isCurr = '0';
            if ($fccode == $value['fCCode']) {
                $isCurr = '1';
            }
            $userAuthList[$key]['isCurr'] = $isCurr;
        }
        return $userAuthList;
    }

    /**
     * 获取用户授权列表 (带主、子账号权限标识)
     * @param   array $userFind 用户对象
     * @return  array           数组集合对象数据
     */
    public function getUserAuthListToHasBuyUserFind($userFind) {
        $user_uuid = $userFind['user_uuid'];
        $fccode = $userFind['fccode'];
        if (empty($user_uuid)) {
            return SFTools::err("3300");
        }
        if (empty($fccode)) {
            return SFTools::err("3300");
        }
        $cstMstLogic = new \backend\logic\CstMstLogic;
        $field = 'ua.fCCode,ua.is_private,ua.create_time,u.login_account,u.accout_state';
        $userAuthList = Db::name('user_auth')->alias('ua')->field($field)
            ->join('aip_user u', 'ua.user_uuid = u.user_uuid')
            ->where('u.user_uuid', $user_uuid)->order('create_time', 'ASC')->select();
        foreach ($userAuthList as $key => $value) {
            $cstMstFind = $cstMstLogic->getCstMstFindBuyFccode($value['fCCode']);
            $isAdmin = '0';
            $fTel = trim($cstMstFind['fTel']);
            if (!preg_match(PREG_MATCH_PHONE, $fTel)) {
                $isAdmin = '1';
            }
            else {
                if ($value['accout_state'] == '1' && $fTel == $value['login_account']) {
                    $isAdmin = '2';
                }
            }
            $userAuthList[$key]['isAdmin'] = $isAdmin;
            $isCurr = '0';
            if ($fccode == $value['fCCode']) {
                $isCurr = '1';
            }
            $userAuthList[$key]['isCurr'] = $isCurr;
            $userAuthList[$key]['mkCode'] = $cstMstFind['mkCode'];
        }
        return $userAuthList;
    }

    /**
     * 获取用户授权列表 (带主、子账号权限标识)
     * @param   string $fccode   经销商编码
     * @param   array  $userFind 用户对象
     * @return  array            数组集合对象数据
     */
    public function getSettingUserAuthListBuyFccode($fccode, $userFind) {
        $user_uuid = $userFind['user_uuid'];
        if (empty($user_uuid)) {
            return SFTools::err("3300");
        }
        if (empty($fccode)) {
            return SFTools::err("3300");
        }
        $bool = $this->checkUserAuth($fccode, $user_uuid);
        if ($bool !== true) {
            return $bool;
        }
        $field = 'ua.user_uuid,ua.fCCode,ua.is_private,ua.create_time,u.login_account';
        $userAuthList = Db::name('user_auth')->alias('ua')->field($field)->join('aip_user u', 'ua.user_uuid = u.user_uuid')->where('ua.fCCode', $fccode)->order('create_time', 'ASC')->select();
        return $userAuthList;
    }

    /**
     * 绑定用户权限（授权人是申请用户则直接绑定，授权人非申请用户则发送授权码）
     * @param   string $fccode   经销商编码
     * @param   array  $userFind 用户对象
     * @return  array             数组集合对象数据
     */
    public function bingUserAuth($fccode, $userFind) {
        if (empty($fccode)) {
            return SFTools::err("3300");
        }
        $user_uuid = $userFind['user_uuid'];
        if (empty($user_uuid)) {
            return SFTools::err("3300");
        }
        $userAuth = new \backend\model\UserAuth;
        $field = 'user_auth_uuid,user_uuid,fCCode,is_private';
        $userAuthFind = $userAuth::field($field)->where('user_uuid', $user_uuid)->where('fCCode', $fccode)->find();
        if (empty($userAuthFind)) {
            $cstMst = new \backend\model_erp\CstMst;
            $cstMstFind = $cstMst::field('fTel')->where('fCCode', $fccode)->find();
            if (empty($cstMstFind)) {
                return SFTools::err("3902");
            }
            $user = new \backend\model\User();
            $userFind = $user::field('login_account')->where('user_uuid', $user_uuid)->find();
            if (empty($userFind)) {
                return SFTools::err("3300");
            }
            $phone = trim($userFind['login_account']);
            $fTel = trim($cstMstFind['fTel']);
            if (!preg_match(PREG_MATCH_PHONE, $fTel)) {
                return SFTools::err("3901");
            }
            //授权人是申请用户则直接绑定
            if ($fTel == $phone) {
                $this->saveUserAuthFind($fccode, $user_uuid);
                return '';
            }
            $oauthLogic = new \backend\logic\OauthLogic;
            return $oauthLogic->getOauthFindBuyFccodeAndPhonefTel($fccode, $phone, $fTel);
        }
        return NULL;
    }

    /**
     * 申请授权码
     * @param   string $fccode   经销商编码
     * @param   array  $userFind 用户对象
     * @return  array            数组集合对象数据
     */
    public function getAppleCodeForUserAuth($fccode, $userFind) {
        if (empty($fccode)) {
            return SFTools::err("3300");
        }
        $user_uuid = $userFind['user_uuid'];
        if (empty($user_uuid)) {
            return SFTools::err("3300");
        }
        $userAuth = new \backend\model\UserAuth;
        $field = 'user_auth_uuid,user_uuid,fCCode,is_private';
        $userAuthFind = $userAuth::field($field)->where('user_uuid', $user_uuid)->where('fCCode', $fccode)->find();
        if (empty($userAuthFind)) {
            return SFTools::err("3310");
        }
        $cstMst = new \backend\model_erp\CstMst;
        $cstMstFind = $cstMst::field('fTel')->where('fCCode', $fccode)->find();
        if (empty($cstMstFind)) {
            return SFTools::err("3902");
        }
        $user = new \backend\model\User();
        $userFind = $user::field('login_account')->where('user_uuid', $user_uuid)->find();
        if (empty($userFind)) {
            return SFTools::err("3300");
        }
        $phone = trim($userFind['login_account']);
        $fTel = trim($cstMstFind['fTel']);
        if (!preg_match(PREG_MATCH_PHONE, $fTel)) {
            return SFTools::err("3901");
        }
        $oauthLogic = new \backend\logic\OauthLogic;
        return $oauthLogic->getOauthFindBuyFccodeAndPhonefTel($fccode, $phone, $fTel, "LAO");
    }

    /**
     * 给出正确的手机号码验证后绑定经销商编码
     * @param   string $fccode   订单号
     * @param   string $phone    电话号码
     * @param   string $pow_code 授权码
     * @return  array            数组对象数据
     */
    public function toBingBuyCode($fccode, $phone, $pow_code) {
        if (empty($fccode)) {
            return SFTools::err("3903");
        }
        if (!preg_match(PREG_MATCH_PHONE, $phone)) {
            return SFTools::err("3311");
        }
        $cstMst = new \backend\model_erp\CstMst;
        $field = "fCCode,fCNName,fCName,fAddress,fTel";
        $cstMstFind = $cstMst::field($field)->where('fCCode', $fccode)->find();
        if (empty($cstMstFind)) {
            return SFTools::err("3902");
        }
        $fTel = trim($cstMstFind['fTel']);
        if (!preg_match(PREG_MATCH_PHONE, $fTel)) {
            return SFTools::err("3901");
        }
        // 生成 cache_key
        $cache_key = md5("LO{$fccode}{$phone}");
        // 获取缓存对象
        $cache_arr = SFTools::getCache($cache_key);
        if (empty($cache_arr)) {
            return SFTools::err("3904");
        }
        if (empty($cache_arr['pow_code']) || $cache_arr['pow_code'] != $pow_code) {
            return SFTools::err("3906");
        }
        $result = $this->saveUserAuthFindBuyFccodeAndPhone($fccode, $phone);
        if (empty($result['error_code'])) {
            SFTools::setCache($cache_key, NULL);
        }
        return $result;
    }

    /**
     * 新增用户授权
     * @param   string $fccode   经销商编码
     * @param   array  $userFind 用户对象
     * @param   array  $pow_code 授权编码
     * @return  array             数组集合对象数据
     */
    public function addUserAuth($fccode, $userFind, $pow_code, $prefix = "LLO") {
        if (empty($fccode)) {
            return SFTools::err("3903");
        }
        $user_uuid = $userFind['user_uuid'];
        if (empty($user_uuid)) {
            return SFTools::err("3300");
        }
        $user = new \backend\model\User();
        $userFind = $user::field('login_account')->where('user_uuid', $user_uuid)->find();
        if (empty($userFind)) {
            return SFTools::err("3300");
        }
        $phone = $userFind['login_account'];
        // 生成 cache_key
        $cache_key = md5("{$prefix}{$fccode}{$phone}");
        // 获取缓存对象
        $cache_arr = SFTools::getCache($cache_key);
        if (empty($cache_arr)) {
            return SFTools::err("3904");
        }
        if (empty($cache_arr['pow_code']) || $cache_arr['pow_code'] != $pow_code) {
            return SFTools::err("3906");
        }
        $result = $this->saveUserAuthFindBuyFccodeAndPhone($fccode, $phone);
        if (empty($result['error_code'])) {
            SFTools::setCache($cache_key, NULL);
        }
        return $result;
    }

    /**
     * 通过授权码提升用户权限
     * @param   string $fccode   经销商编码
     * @param   array  $userFind 用户对象
     * @param   array  $pow_code 授权编码
     * @return  array             数组集合对象数据
     */
    public function saveUserAuthLevel($fccode, $userFind, $pow_code) {
        $is_private = 1;
        if (empty($fccode)) {
            return SFTools::err("3903");
        }
        $user_uuid = $userFind['user_uuid'];
        if (empty($user_uuid)) {
            return SFTools::err("3300");
        }
        $user = new \backend\model\User();
        $userFind = $user::field('login_account')->where('user_uuid', $user_uuid)->find();
        if (empty($userFind)) {
            return SFTools::err("3300");
        }
        $phone = $userFind['login_account'];
        // 生成 cache_key
        $cache_key = md5("LAO{$fccode}{$phone}");
        // 获取缓存对象
        $cache_arr = SFTools::getCache($cache_key);
        if (empty($cache_arr)) {
            return SFTools::err("3904");
        }
        if (empty($cache_arr['pow_code']) || $cache_arr['pow_code'] != $pow_code) {
            return SFTools::err("3906");
        }
        $userAuth = new \backend\model\UserAuth;
        $userAuthFind = $userAuth::where('user_uuid', $user_uuid)->where('fCCode', $fccode)->find();
        if (empty($userAuthFind) || $is_private == $userAuthFind['is_private']) {
            return SFTools::err("3300");
        }
        else {
            $userAuthFind->is_private = $is_private;
            $userAuthFind->save();
            SFTools::setCache($cache_key, NULL);
        }
        return '';
    }

    /**
     * 切换用户授权
     * @param   string $fccode   经销商编码
     * @param   array  $userFind 用户对象
     * @param   array  $t        缓存键值
     * @return  array             数组集合对象数据
     */
    public function selectUserAuth($fccode, $userFind, $t) {
        if (empty($t)) {
            return SFTools::err("3300");
        }
        if (empty($fccode)) {
            return SFTools::err("3300");
        }
        $user_uuid = $userFind['user_uuid'];
        if (empty($user_uuid)) {
            return SFTools::err("3300");
        }
        $userAuth = new \backend\model\UserAuth;
        $userAuthFind = $userAuth::field('user_auth_uuid,user_uuid,fCCode,is_private')->where('user_uuid', $user_uuid)->where('fCCode', $fccode)->find();
        if (empty($userAuthFind)) {
            return NULL;
        }
        $cstMstLogic = new \backend\logic\CstMstLogic;
        $cstMstFind = $cstMstLogic->getCstMstFindBuyFccode($fccode);
        if(!empty($cstMstFind)){
            $userFind['mkCode'] = $cstMstFind['mkCode'];
        }
        $userFind['fccode'] = $fccode;
        SFTools::setCache($t, $userFind);
        return "";
    }

    /**
     * 删除用户权限，并自动修改
     * @param   string $fccode    经销商编码
     * @param   array  $user_uuid 用户唯一标识
     * @param   array  $userFind  用户对象
     * @param   array  $t         缓存键值
     * @return  array             数组集合对象数据
     */
    public function delUserAuth($fccode, $user_uuid, $userFind, $t) {
        if (empty($t)) {
            return SFTools::err("3300");
        }
        if (empty($fccode)) {
            return SFTools::err("3300");
        }
        if (empty($user_uuid)) {
            return SFTools::err("3300");
        }
        if ($user_uuid != $userFind['user_uuid']) {
            $bool = $this->checkUserAuth($fccode, $userFind['user_uuid']);
            if ($bool !== true) {
                return $bool;
            }
        }
        $userAuth = new \backend\model\UserAuth;
        $userAuthFind = $userAuth::field('user_auth_uuid,user_uuid,fCCode,is_private')->where('user_uuid', $user_uuid)->where('fCCode', $fccode)->find();
        if (empty($userAuthFind)) {
            return NULL;
        }
        $userAuth::where('user_uuid', $user_uuid)->where('fCCode', $fccode)->delete();
        if ($user_uuid == $userFind['user_uuid'] && $fccode == $userFind['fccode']) {
            $field = 'ua.*,u.login_account,u.nickname,u.accout_state';
            $userAuthList = Db::name('user_auth')->alias('ua')->field($field)->join('aip_user u', 'UA.user_uuid = u.user_uuid')->where('u.user_uuid', $user_uuid)->order('create_time', 'ASC')->select();
            if (empty($userAuthList)) {
                SFTools::setCache($t, NULL);
                return "";
            }
            else {
                $fccode = $userAuthList[0]['fCCode'];
                $cstMstLogic = new \backend\logic\CstMstLogic;
                $cstMstFind = $cstMstLogic->getCstMstFindBuyFccode($fccode);
                if(!empty($cstMstFind)){
                    $userFind['mkCode'] = $cstMstFind['mkCode'];
                }
                $userFind['fccode'] = $fccode;
                SFTools::setCache($t, $userFind);
            }
        }
        return $fccode;
    }

    /**
     * 删除用户权限，并自动修改
     * @param   string $fccode    经销商编码
     * @param   array  $user_uuid 用户唯一标识
     * @param   array  $val       状态值
     * @param   array  $userFind  用户对象
     * @return  array             数组集合对象数据
     */
    public function updateUserAuthToIsPrivate($fccode, $user_uuid, $val, $userFind) {
        if ($val != 0 && $val != 1) {
            return SFTools::err("3300");
        }
        $is_private = trim($val);
        if (empty($fccode)) {
            return SFTools::err("3300");
        }
        if (empty($user_uuid)) {
            return SFTools::err("3300");
        }
        if ($user_uuid != $userFind['user_uuid']) {
            $bool = $this->checkUserAuth($fccode, $userFind['user_uuid']);
            if ($bool !== true) {
                return $bool;
            }
        }
        $userAuth = new \backend\model\UserAuth;
        $userAuthFind = $userAuth::where('user_uuid', $user_uuid)->where('fCCode', $fccode)->find();
        if (empty($userAuthFind) || $is_private == $userAuthFind['is_private']) {
            return SFTools::err("3300");
        }
        else {
            $userAuthFind->is_private = $is_private;
            $userAuthFind->save();
        }
        return '';
    }

    /**
     * 检查用户是否是主账号
     * @param   string $fccode    经销商编码
     * @param   array  $user_uuid 用户唯一标识
     * @return  bool              布尔值
     */
    public function checkUserAuth($fccode, $user_uuid) {
        if (empty($fccode)) {
            return SFTools::err("3300");
        }
        if (empty($user_uuid)) {
            return SFTools::err("3300");
        }
        $cstMst = new \backend\model_erp\CstMst;
        $field = "fCCode,fCNName,fCName,fAddress,fTel";
        $cstMstFind = $cstMst::field($field)->where('fCCode', $fccode)->find();
        if (empty($cstMstFind)) {
            return SFTools::err("3902");
        }
        $fTel = trim($cstMstFind['fTel']);
        if (!preg_match(PREG_MATCH_PHONE, $fTel)) {
            return SFTools::err("3901");
        }
        $userLogic = new \backend\logic\UserLogic;
        $userFind = $userLogic->getUserFindBuyUserUUID($user_uuid);
        $phone = trim($userFind['login_account']);
        if ($fTel != $phone) {
            return SFTools::err("3999");
        }
        return true;
    }
}